#include <8052.h>

#define LCD_SCL P1_0
#define LCD_SDA P1_1
#define LCD_RES P1_2
#define LCD_DC P1_3
#define LCD_CS P1_4
#define LCD_BLK P1_5

#define CMD 0
#define DATA 1

static void spi_send(char data, int is_data)
{
    LCD_DC = is_data;
    LCD_CS = 0;
    for (int j = 7; j >= 0; j--)
    {
        LCD_SDA = (data >> j) & 1;
        LCD_SCL = 0;
        LCD_SCL = 1;
    }
    LCD_CS = 1;
}

static void spi_send_w(int data, int is_data)
{
    LCD_DC = is_data;
    LCD_CS = 0;
    for (int j = 15; j >= 0; j--)
    {
        LCD_SDA = (data >> j) & 1;
        LCD_SCL = 0;
        LCD_SCL = 1;
    }
    LCD_CS = 1;
}

void lcd_init(void)
{
    LCD_RES = 0;
    LCD_RES = 1;
    spi_send(0x01, CMD);
    spi_send(0x11, CMD);
    spi_send(0x3a, CMD);
    spi_send(0x05, DATA);
    spi_send(0x36, CMD);
    spi_send(0xC0, DATA);
    spi_send(0x29, CMD);
}

void lcd_fill(int x_begin, int x_end, int y_begin, int y_end, int r, int g, int b)
{
    int size = (x_end - x_begin) * (y_end - y_begin);
    spi_send(0x2a, CMD);
    spi_send_w(x_begin, DATA);
    spi_send_w(x_end - 1, DATA);
    spi_send(0x2b, CMD);
    spi_send_w(y_begin, DATA);
    spi_send_w(y_end - 1, DATA);
    spi_send(0x2c, CMD);
    int color = (b >> 3 << 11) | (g >> 2 << 5) | (r >> 3);
    for (int i = 0; i < size; i++)
    {
        spi_send_w(color, DATA);
    }
}
